package xin.yangshuai.cipher.des;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Des
 *
 * @author shuai
 * @date 2020/11/22
 */
public class Des {

    public static void main(String[] args) throws Exception {
        ecb();
        cbc();
    }

    public static void ecb() throws Exception {

        String text = "hello world";
        // DES默认加密模式ECB
        Cipher cipher0 = Cipher.getInstance("DES");
        //密钥是8个字节
        String key = "12345678";
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "DES");

        //设置为加密
        cipher0.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] bytes = cipher0.doFinal(text.getBytes());
        String encode = Base64.encode(bytes);
        System.out.println(encode);

        //设置为解密
        Cipher cipher1 = Cipher.getInstance("DES");
        cipher1.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] bytes1 = cipher1.doFinal(Base64.decode(encode));
        String s = new String(bytes1);
        System.out.println(s);
    }

    public static void cbc() throws Exception {

        String text = "hello world";
        // 加密模式（CBC），填充模式（PKCS5Padding）
        Cipher cipher0 = Cipher.getInstance("DES/CBC/PKCS5Padding");
        // 密钥是8个字节
        String key = "12345678";

        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "DES");
        // iv向量必须8个字节
        IvParameterSpec ivParameterSpec = new IvParameterSpec("12345678".getBytes());

        // 设置为加密
        cipher0.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] bytes = cipher0.doFinal(text.getBytes());
        String encode = Base64.encode(bytes);
        System.out.println(encode);

        //设置为解密
        Cipher cipher1 = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher1.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] bytes1 = cipher1.doFinal(Base64.decode(encode));
        String s = new String(bytes1);
        System.out.println(s);
    }
}
